/**
 * @Description: 多人拼团
 * @author ourslookAdmin
 * @date 2019-04-28 10:22:27
 */
import React, { Fragment } from 'react';
import {
  Button,
  Card,
  Checkbox,
  Col,
  Divider,
  DatePicker,
  TimePicker,
  Form,
  Input,
  InputNumber,
  Radio,
  Row,
  Select,
  Spin,
  Tag,
  TreeSelect,
  Tooltip,
  Table,
  Icon,
  BackTop,
} from 'antd';
import moment from 'moment';
import { formatMessage, FormattedMessage } from 'umi/locale';
import 'antd/dist/antd.css';
import PropTypes from 'prop-types';
import { connect } from 'dva';
import { requestLists, requestPromise } from '@/utils/request';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import BaseForm from '../../../components/ourslook/BaseForm';
import ETable from '../../../components/ourslook/ETable';
import { getWebPath } from '../../../utils/request';
import uiUtils, { hasPermission, rulesReg, rulesRemote } from '../../../utils/uiUtils';
import styles from '../../../utils/ourslook.less';
import Ellipsis from '../../../components/ourslook/Ellipsis';
import DefaultImage from "../../../components/ourslook/DefaultImage";

const FormItem = Form.Item;
const Option = Select.Option;
const RadioGroup = Radio.Group;
const TextArea = Input.TextArea;
const Password = Input.Password;
const CheckboxGroup = Checkbox.Group;
const { MonthPicker, RangePicker, WeekPicker } = DatePicker;

const getValue = obj =>
  Object.keys(obj)
    .map(key => obj[key])
    .join(',');

// @coming({title: '精彩即将呈现！', value: Date.now() + 1000 * 60 * 60 * 24 * 2})
@connect(() => ({}))
class Groupon extends React.Component {
  params = {
    page: 1,
    limit: 10,
  };

  formItemLayout = {
    labelCol: { span: 5 },
    wrapperCol: { span: 19 },
  };

  /**
   * https://ant-design.gitee.io/components/table-cn/
   *
   * 需要指定 column 的 width 属性，否则列头和内容可能不对齐。（必须留一列不设宽度或者minWidth以适应弹性布局）
   * 建议指定 scroll.x 为大于表格宽度的固定值或百分比。注意，且非固定列宽度之和不要超过 scroll.x, 一般无table正常展开的宽度
   * 未知长度字段或者字符特别多的字段不要放置在列表
   */
  columns = [
    {
      title: '',
      width: 30,
      align: 'center',
      fixed: 'left',
      render: (value, record, index) => index + 1,
    },
    {
      title: '活动名称',
      dataIndex: 'title',
      width: 200,
      align: 'center',
      sorter: false,
      render: value => (
        <Ellipsis length={10} tooltip>
          {value}
        </Ellipsis>
      ),
    },
    {
      title: '商品名称',
      dataIndex: 'productName',
      width: 150,
      align: 'center',
      sorter: false,
      render: value => (
        <Ellipsis length={10} tooltip>
          {value}
        </Ellipsis>
      ),
    },
    {
      title: '有效时间',
      dataIndex: 'startTime',
      align: 'center',
      sorter: false,
      render: (value, record, index) => {
        if (record.startTime && record.endTime) {
          return `${record.startTime} 至 ${record.endTime}`;
        }
        return '';
      },
    },
    {
      title: '活动状态',
      dataIndex: 'status',
      width: 100,
      align: 'center',
      sorter: false,
      render: (value, record, index) => {
        let status = '';
        if (record.status === 1) {
          const startTime = moment(record.startTime).format('X');
          const endTime = moment(record.endTime).format('X');
          const nowTime = moment().format('X');
          if (startTime < nowTime && nowTime < endTime) {
            status = (
              <Tag style={{ cursor: 'default' }} className={styles.label_success}>
                正在进行中
              </Tag>
            );
          } else if (endTime < nowTime) {
            status = (
              <Tag style={{ cursor: 'default' }} className={styles.label_warning}>
                已结束
              </Tag>
            );
          } else if (nowTime < startTime) {
            status = (
              <Tag style={{ cursor: 'default' }} className={styles.label_primary}>
                未开始
              </Tag>
            );
          } else {
            status = (
              <Tag style={{ cursor: 'default' }} className={styles.label_danger}>
                已失效
              </Tag>
            );
          }
        } else if (record.status === 0) {
          status = (
            <Tag style={{ cursor: 'default' }} className={styles.label_danger}>
              已失效
            </Tag>
          );
        } else {
          status = '- -';
        }
        return status;
      },
    },
    {
      title: '微信二维码',
      dataIndex: 'wxQrCode',
      width: 100,
      align: 'center',
      sorter: false,
      render: (value, record, index) =>
        value === undefined ? (
          <Tag style={{ cursor: 'default' }} className={styles.label_primary}>
            未生成
          </Tag>
        ) : (
          <Tag style={{ cursor: 'default' }} className={styles.label_success}>
            已生成
          </Tag>
        ),
    },
    { title: '成团人数', dataIndex: 'joinNum', width: 100, align: 'center', sorter: false },
    {
      title: '订单实付金额',
      dataIndex: 'voOrderTotalMoney',
      width: 120,
      align: 'center',
      sorter: false,
      render: (value, record, index) => {
        if (!value) {
          return '- -';
        }
        return value;
      },
    },
    {
      title: '付款订单数',
      dataIndex: 'voOrderTotalNum',
      width: 120,
      align: 'center',
      sorter: false,
      render: (value, record, index) => {
        if (!value) {
          return '- -';
        }
        return value;
      },
    },
    {
      title: '付款人数',
      dataIndex: 'voOrderTotalUser',
      width: 100,
      align: 'center',
      sorter: false,
      render: (value, record, index) => {
        if (!value) {
          return '- -';
        }
        return value;
      },
    },
    {
      title: '操作',
      dataIndex: '',
      width: 170,
      align: 'center',
      fixed: 'right',
      render: (value, record, index) => (
        <React.Fragment>
          <a
            hidden={record.status === 0}
            onClick={() => {
              this.setStateByTableColume(record, index);
              this.update();
            }}
          >
            <Tooltip title={<FormattedMessage id="ours.curd.list.edit" defaultMessage="编辑" />}>
              <Icon type="edit" />
            </Tooltip>
          </a>
          <Divider hidden={record.status === 0} type="vertical" />
          <a
            onClick={() => {
              this.setStateByTableColume(record, index);
              this.view();
            }}
          >
            <Tooltip title={<FormattedMessage id="ours.curd.list.info" defaultMessage="查看" />}>
              <Icon type="info" />
            </Tooltip>
          </a>
          <Divider type="vertical" />
          <a
            onClick={() => {
              this.createWxImage(record, index);
            }}
          >
            <Tooltip
              title={
                <FormattedMessage id="ours.curd.list.createWxImage" defaultMessage="生成二维码" />
              }
            >
              <Icon type="file-image" />
            </Tooltip>
          </a>
          <Divider hidden={record.status !== 1} type="vertical" />
          <a
            hidden={record.status !== 1}
            onClick={() => {
              this.setStateByTableColume(record, index);
              this.failure();
            }}
          >
            {/*<Tooltip title={<FormattedMessage id="ours.curd.list.info" defaultMessage="查看" />}>*/}
            {/*  <Icon type="info" />*/}
            {/*</Tooltip>*/}
            <span>使失效</span>
          </a>
        </React.Fragment>
      ),
    },
    // {title: 'tenantId多租户使用', dataIndex: 'tenantId', width: 120, align: 'center', sorter: false},
    // {title: '状态', dataIndex: 'status', width: 120, align: 'center', sorter: false},
    // {title: '创建人', dataIndex: 'createUser', width: 120, align: 'center', sorter: false},
    // {title: 'createTime', dataIndex: 'createTime', width: 190, align: 'center', sorter: true},
    // {title: '更新人', dataIndex: 'updateUser', width: 120, align: 'center', sorter: false},
    // {title: 'updateTime', dataIndex: 'updateTime', width: 190, align: 'center', sorter: true},
    // {
    //   title: '状态',
    //   dataIndex: 'status',
    //   width: 30,
    //   align: 'center',
    //   fixed: 'right',
    //   render: (value, record, index) =>
    //     value === 0 ? (
    //       <Tag style={{ cursor: 'default' }} className={styles.label_success}>
    //         正常
    //       </Tag>
    //     ) : (
    //       <Tag style={{ cursor: 'default' }} className={styles.label_danger}>
    //         暂停
    //       </Tag>
    //     ),
    // },
  ];

  constructor(props) {
    super(props);
    this.state = {
      showList: 1, //1:显示列表、2:显示新增
      formList: Groupon.getFormList(),
      selectedRows: [],
      selectedIds: [],
      selectedIndexs: [],
      editModalTitle: null,
      editModalType: null,
      editModel: null,
      editModelConfirmLoading: false,
      //其他属性下面书写
    };
  }

  // 筛选条件
  static getFormList = () => [
    {
      type: 'INPUT',
      field: 'productName',
      label: '商品名称',
      placeholder: '商品名称',
    },
    {
      type: 'INPUT',
      field: 'title',
      label: '活动名称',
      placeholder: '活动名称',
    },
    {
      type: 'DATE_RANGE',
      field: 'startTime',
      label: '有效时间',
      placeholder: ['有效时间', '结束时间'],
    },
    {
      type: 'SELECT',
      field: 'status',
      label: '状态',
      initialValue: '',
      placeholder: '状态',
      list: [
        { id: '', name: '请选择状态' },
        { id: '1', name: '进行中' },
        { id: '2', name: '未开始' },
        { id: '3', name: '已结束' },
        {
          id: '0',
          name: '已失效',
        },
      ],
      showSearch: true,
    },
    //下面是各种组件的示例代码，不用 请删除不需要的代码和注释
  ];

  componentDidMount() {
    this.requestList();
  }

  componentWillUnmount() {}

  /**
   * 根据 formItem field 取值 查找formItem
   * @param formItemField obj的field字段
   * @returns 一个对象
   */
  findFormListItemByField = formItemField =>
    this.state.formList.find((value, index, array) => value.field === formItemField);

  query = fieldParams => {
    this.params = JSON.parse(JSON.stringify(Object.assign(this.params, fieldParams)));
    this.requestList();
  };

  add = () => {
    this.setState({
      editModalType: 'add',
      editModalTitle: formatMessage({ id: 'ours.curd.list.create' }), //创建
      editModel: {
        autoGroupEnabled: true,
        limitNumStatus: false
      },
      showList: 2,
    });
    this.initTimeSelect();
  };

  update = () => {
    const { selectedRows, selectedIds, selectedIndexs } = this.state;
    if (!selectedRows) {
      uiUtils.showAlert(formatMessage({ id: 'ours.curd.show-alert.select-please' }));
      return;
    }
    if (selectedRows.length > 1) {
      uiUtils.showAlert(formatMessage({ id: 'ours.curd.show-alert.select-one-please' }));
      return;
    }
    if (selectedRows[0].status === 0) {
      uiUtils.showAlert('失效活动无法修改！');
      return;
    }
    selectedRows[0].limitNumStatus = selectedRows[0].limitNum > 0;
    this.setState({
      editModalType: 'update',
      editModalTitle: <FormattedMessage id="ours.curd.list.edit" defaultMessage="编辑" />,
      editModel: JSON.parse(JSON.stringify(selectedRows[0])),
      showList: 2,
    });
    this.getInfo(selectedRows[0].grouponId);
  };

  view = () => {
    const { selectedRows, selectedIds, selectedIndexs } = this.state;
    if (!selectedRows) {
      uiUtils.showAlert(formatMessage({ id: 'ours.curd.show-alert.select-please' }));
      return;
    }
    if (selectedRows.length > 1) {
      uiUtils.showAlert(formatMessage({ id: 'ours.curd.show-alert.select-one-please' }));
      return;
    }
    selectedRows[0].limitNumStatus = selectedRows[0].limitNum > 0;
    this.setState({
      editModalType: 'view',
      editModalTitle: <FormattedMessage id="ours.curd.list.info" defaultMessage="查看" />,
      editModel: selectedRows[0],
      showList: 2,
    });
    this.getInfo(selectedRows[0].grouponId);
  };

  del = () => {
    const selectedRows = this.state.selectedRows;
    const grouponIds = [];
    for (let i = 0; i < selectedRows.length; i += 1) {
      if (selectedRows[i].status !== 0) {
        uiUtils.showAlert('只有无效的活动才可以删除');
        return;
      }
      grouponIds.push(selectedRows[i].grouponId);
    }

    uiUtils.showConfirm(formatMessage({ id: 'ours.curd.show-alert.confirm-delete' }), () => {
      this.setState({
        loading: true,
      });
      requestPromise(`${getWebPath()}promotiongroupon/delete`, {
        method: 'POST',
        body: grouponIds,
      }).then(res => {
        this.setState({
          loading: false,
        });
        if (res && res.code === 0) {
          uiUtils.showMessage(
            formatMessage({ id: 'ours.curd.show-alert.operate-success' }),
            'success'
          );
          this.requestList();
        }
      });
    });
  };

  createWxImage = (record, index) => {
    //此处如果它的类型值为空， 为了不让下面的接口出现异常，这里传入-1， -1 在接口中也代表该值不存在
    if (record.wxQrCode) {
      uiUtils.showConfirm(formatMessage({ id: '已经存在二维码，是否再次生成？' }), () => {
        requestPromise(
          `${getWebPath(
            `/promotiongroupon/createWxImage?grouponId=${record.grouponId}`
          )}`,
          {
            method: 'GET',
          }
        ).then(res => {
          if (res && res.code === 0) {
            uiUtils.showMessage('操作成功');
            this.requestList();
          }
        });
      });
    } else {
      uiUtils.showConfirm(formatMessage({ id: '是否生成二维码？' }), () => {
        requestPromise(
          `${getWebPath(
            `/promotiongroupon/createWxImage?grouponId=${record.grouponId}`
          )}`,
          {
            method: 'GET',
          }
        ).then(res => {
          if (res && res.code === 0) {
            uiUtils.showMessage('操作成功');
            this.requestList();
          }
        });
      });
    }
  };

  failure = () => {
    const selectedRows = this.state.selectedRows;
    const grouponIds = [];
    for (let i = 0; i < selectedRows.length; i += 1) {
      if (selectedRows[i].status !== 1) {
        uiUtils.showAlert('只有正常的活动才可以使其无效');
        return;
      }
      grouponIds.push(selectedRows[i].grouponId);
    }

    uiUtils.showConfirm(formatMessage({ id: 'ours.curd.show-alert.confirm-failure' }), () => {
      this.setState({
        loading: true,
      });
      requestPromise(`${getWebPath()}promotiongroupon/failure`, {
        method: 'POST',
        body: grouponIds,
      }).then(res => {
        this.setState({
          loading: false,
        });
        if (res && res.code === 0) {
          uiUtils.showMessage(
            formatMessage({ id: 'ours.curd.show-alert.operate-success' }),
            'success'
          );
          this.requestList();
        }
      });
    });
  };

  saveOrUpdate = () => {
    const editModalType = this.state.editModalType;
    //不能双向绑定，这里只能原对象、新对象进行合并.
    const promotionGroupon = Object.assign(
      this.state.editModel,
      this.editForm.props.form.getFieldsValue()
    );

    this.editForm.props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        // submit the values
        const url =
          promotionGroupon.grouponId == null
            ? '/promotiongroupon/save'
            : '/promotiongroupon/update';
        //对象删除一个属性
        //delete promotionGroupon.xxxxPros;

        if (promotionGroupon.limitNumStatus && (promotionGroupon.limitNum === undefined || promotionGroupon.limitNum <= 0)) {
          uiUtils.showMessage(`限购人数不能为空或者不能小于0！`, 'error');
          return;
        }

        this.setState({
          editModelConfirmLoading: true,
        });

        const regex = /^grouponPrice-(\d+)&/;
        const productSpecs = [];
        Object.keys(promotionGroupon).forEach(key => {
          if (key.indexOf('grouponPrice-') !== -1) {
            const spec = {
              id: key.split('-')[1],
              grouponPrice: promotionGroupon[key],
            };
            productSpecs.push(spec);
          }
        });
        promotionGroupon.productSpecs = productSpecs;
        promotionGroupon.groupType = 1;
        promotionGroupon.startTime = `${promotionGroupon.startTimeBetween[0].format(
          'YYYY-MM-DD'
        )} 00:00:00`;
        promotionGroupon.endTime = `${promotionGroupon.startTimeBetween[1].format(
          'YYYY-MM-DD'
        )} 23:59:59`;
        promotionGroupon.delayTime =
          (promotionGroupon.delayTimeDay * 24 * 60 +
            promotionGroupon.delayTimeHour * 60 +
            promotionGroupon.delayTimeMin * 1) *
          60;

        requestPromise(getWebPath() + url, {
          method: 'POST',
          body: promotionGroupon,
        }).then(res => {
          this.setState({
            editModelConfirmLoading: false,
          });
          if (res && res.code === 0) {
            uiUtils.showMessage(
              formatMessage({ id: 'ours.curd.show-alert.operate-success' }),
              'success'
            );
            this.setState({
              showList: 1,
            });

            //新增重新置为第一页
            if (!promotionGroupon.grouponId) {
              this.params.page = 1;
            }
            this.requestList();
          }
        });
      }
    });
  };

  getInfo = (grouponId, productId) => {};

  initTimeSelect = () => {
    const days = [];
    for (let i = 0; i < 30; i += 1) {
      if (i.toString().length === 1) {
        days.push(`<option key=0{i}>0{i}</option>`);
      } else {
        days.push(`<option key={i}>{i}</option>`);
      }
    }
    return days;
  };

  setStateByTableColume = (record, index) => {
    this.state = {
      ...this.state,
      selectedRows: [record],
      selectedIds: [record.grouponId],
      selectedIndexs: [index],
    };
  };

  operateByIds = status => {
    //这里处理，发布、取消发布、删除、禁用等状态操作; 参数status由调用放传入
    // const {selectedRows, selectedIds, selectedIndexs} = this.state;
    // const ids = [];
    // for (let i = 0; i < selectedRows.length; i += 1) {
    //   // if (status === 0) {
    //   //   if (selectedRows[i].status !== 1) {
    //   //     alert("只有正常的活动才可以使无效");
    //   //     return;
    //   //   }
    //   // }
    //   ids.push(selectedRows[i].grouponId);
    // }
    //
    // /* eslint-disable no-param-reassign */
    // status = status === undefined ? 3 : status;
    // let tips = "请确定是否要进行操作??????";
    // let msgIds = null;
    // if (status === 2) {
    //   msgIds = 'ours.curd.show-alert.confirm-publish';//发布
    // } else if (status === 3) {
    //   msgIds = 'ours.curd.show-alert.confirm-delete';//删除
    // } else if (status === 1) {
    //   tips = "请选择要撤消选中项吗？";
    //   msgIds = 'ours.curd.show-alert.confirm-enable';//启用
    // } else if (status === -1) {
    //   msgIds = 'ours.curd.show-alert.confirm-disable';//禁用
    // } else if (status === 0) {
    //   msgIds = 'ours.curd.show-alert.confirm-failure';//禁用
    // }
    //
    // console.log(status);
    //
    // uiUtils.showConfirm(formatMessage({id: msgIds}), () => {
    //   this.setState({
    //     loading: true,
    //   });
    //   //const data = 'modelIds=' + ids.join(',') + '&status=' + status;
    //   const data = {
    //     modelIds: ids.join(','),
    //     status: status,
    //   };
    //   requestPromise(`${getWebPath()}promotiongroupon/operatePromotionGrouponByGrouponIds`, {
    //     method: 'POST',
    //     contentType: "application/x-www-form-urlencoded",
    //     body: data,
    //   }).then(res => {
    //     this.setState({
    //       loading: false,
    //     });
    //     if (res && res.code === 0) {
    //       uiUtils.showMessage(
    //         formatMessage({id: 'ours.curd.show-alert.operate-success'}),
    //         'success'
    //       );
    //       this.requestList();
    //     }
    //   });
    // });
  };

  //========其他所有的处理方法，请在按照约定进行处理==========

  /**
   * 表格 筛选和排序 回调
   */
  filtersSorterChange = tableParams => {
    this.params = JSON.parse(JSON.stringify(Object.assign(this.params, tableParams)));
    this.requestList();
  };

  requestList = () => {
    requestLists(this, `${getWebPath()}promotiongroupon/list`, this.params);
  };

  vShow = showListNum => ({ display: this.state.showList === showListNum ? 'block' : 'none' });

  render() {
    const style = {
      style: {
        marginLeft: 10,
        marginTop: 10,
      },
      disabled: this.state.selectedIndexs.length <= 0,
    };

    /* eslint-disable react/jsx-no-bind */
    return (
      <PageHeaderWrapper title="">
        <Card
          bordered={false}
          style={{ ...this.vShow(1) }}
          className={styles.oursCard}
          bodyStyle={{ padding: '20px' }}
        >
          <BaseForm
            formList={this.state.formList}
            loading={this.state.loading}
            filterSubmit={this.query}
          />

          <Fragment>
            <Button
              type="primary"
              icon="plus"
              onClick={this.add}
              hidden={!hasPermission('promotiongroupon:save')}
            >
              <FormattedMessage id="ours.curd.list.add" defaultMessage="新增" />
            </Button>
            {/*<Button*/}
            {/*  type="primary"*/}
            {/*  icon="edit"*/}
            {/*  {...style}*/}
            {/*  onClick={this.update}*/}
            {/*  hidden={!hasPermission('promotiongroupon:update')}*/}
            {/*>*/}
            {/*  <FormattedMessage id="ours.curd.list.update" defaultMessage="修改" />*/}
            {/*</Button>*/}
            {/*<Button*/}
            {/*  type="primary"*/}
            {/*  icon="info-circle"*/}
            {/*  {...style}*/}
            {/*  onClick={this.view}*/}
            {/*  hidden={!hasPermission('promotiongroupon:info')}*/}
            {/*>*/}
            {/*  <FormattedMessage id="ours.curd.list.info" defaultMessage="查看" />*/}
            {/*</Button>*/}
            <Button
              type="danger"
              icon="delete"
              {...style}
              onClick={this.del}
              hidden={!hasPermission('promotiongroupon:delete')}
            >
              <FormattedMessage id="ours.curd.list.delete" defaultMessage="删除" />
            </Button>
            {/*<Button*/}
            {/*  type="default"*/}
            {/*  icon="info-circle"*/}
            {/*  {...style}*/}
            {/*  onClick={this.operateByIds(1)}*/}
            {/*  hidden={!hasPermission('promotiongroupon:update')}*/}
            {/*>*/}
            {/*  <FormattedMessage id="ours.curd.list.enable" defaultMessage="启用"/>*/}
            {/*</Button>*/}
            <Button
              type="default"
              icon="info-circle"
              {...style}
              onClick={this.failure}
              hidden={!hasPermission('promotiongroupon:delete')}
            >
              <FormattedMessage id="ours.curd.list.failure" defaultMessage="使失效" />
            </Button>
          </Fragment>

          <div className="content-wrap">
            <ETable
              onSelectRow={uiUtils.onSelectRow.bind(this)}
              primaryKey="groupon_id"
              selectedRows={this.state.selectedRows}
              selectedIds={this.state.selectedIds}
              selectedIndexs={this.state.selectedIndexs}
              onChange={this.filtersSorterChange}
              columns={this.columns}
              dataSource={this.state.list}
              pagination={this.state.pagination}
              loading={this.state.loading}
              scroll={{ x: 1450 }}
            />
          </div>
        </Card>

        <BackTop />

        <Spin spinning={this.state.editModelConfirmLoading} delay={10}>
          {//返回null,这里对不用的组件进行销毁
          this.state.showList === 1 ? null : (
            <Card
              title={this.state.editModalTitle}
              bordered={false}
              actions={[
                <div>
                  <React.Fragment>
                    <Button
                      type="primary"
                      hidden={this.state.editModalType === 'view'}
                      style={{ marginRight: '18px' }}
                      onClick={this.saveOrUpdate}
                    >
                      <FormattedMessage id="ours.curd.add.save" defaultMessage="保存" />
                    </Button>
                    <Button
                      style={{ marginRight: '18px' }}
                      onClick={() => {
                        this.editForm.props.form.resetFields();
                        this.setState({ showList: 1 });
                      }}
                    >
                      <FormattedMessage id="ours.curd.add.back" defaultMessage="返回" />
                    </Button>
                  </React.Fragment>
                </div>,
              ]}
              style={{ ...this.vShow(2) }}
              bodyStyle={{ padding: '20px' }}
              ref={node => {
                this.container = node;
              }}
            >
              <EditForm
                type={this.state.editModalType}
                model={this.state.editModel}
                wrappedComponentRef={inst => {
                  this.editForm = inst;
                }}
              />
            </Card>
          )}
        </Spin>
      </PageHeaderWrapper>
    );
  }
}

export default Groupon;

/**
 *  新增、编辑、复制、查看的Form
 */

/* eslint react/no-multi-comp:0 */
class EditForm extends React.Component {
  static propTypes = {
    type: PropTypes.string, //form类型，可选值：add（增加）、update（修改）、copy（复制）、view（查看）、
    model: PropTypes.object, //数据模型model，对应后台的model
  };

  static defaultProps = {
    type: '', //表单布局数组
    model: null,
  };

  constructor(props) {
    super(props);
    this.productSearch();
    this.state = {};
  }

  /**
   * 生命周期-属性发生变化...componentWillReceiveProps
   * 这里的nextProps，可以获取到所有的属性。
   * 目前没用，因为 dialog 每次都被销毁了
   */
  componentWillReceiveProps(nextProps) {
    if (nextProps.model) {
      // this.state = {};
      //使用setFieldsValue实现修改form value的值，不用使用 this.setState({});
      // this.props.model.xxx = 'value';
      // this.props.form.setFieldsValue({xxx: 'value'});
    }
  }

  getPropsByKey = prop => {
    const model = this.props.model || {};
    const finalModel = Object.assign(model, this.props.form.getFieldsValue());
    return finalModel[prop];
  };

  productSearch = value => {
    // this.setState({
    //   productChildren: []
    // });
    requestPromise(
      `${getWebPath(
        `/mailproduct/listVo?status=2&not_IN_groupon_product=1&productName=${
          value === undefined ? '' : value
        }`
      )}`,
      {
        method: 'GET',
      }
    ).then(res => {
      if (res && res.code === 0) {
        const datas = res.page.list || [];
        const results = [];
        datas.forEach(r => {
          if (r.id !== this.props.model.productId) {
            results.push(<Option key={r.id}>{r.productName}</Option>);
          }
        });
        this.setState({
          productChildren: results,
        });
      }
    });
  };

  productChange = val => {
    requestPromise(`${getWebPath(`/mailproduct/infoVo/${val}`)}`, {
      method: 'GET',
    }).then(res => {
      if (res && res.code === 0) {
        const result = res.mailProduct;
        const specResults = result.productSpecs;
        const dataSource = [];
        specResults.forEach(r => {
          r.grouponPrice = 0;
          let productss = '';
          if (r.productSpecs !== undefined) {
            const productSpecs = JSON.parse(r.productSpecs);
            productSpecs.forEach(s => {
              // eslint-disable-next-line guard-for-in,no-restricted-syntax
              for (const key in s) {
                productss = productss === '' ? s[key] : `${productss},${s[key]}`;
              }
            });
          }
          r.productSpecs = productss;
          dataSource.push(r);
        });
        this.setState({
          title: result.productName,
          data: dataSource,
        });
      }
    });
  };

  getProductInfo = productId => {
    if (productId !== undefined) {
      requestPromise(`${getWebPath(`/mailproduct/infoVo/${productId}`)}`, {
        method: 'GET',
      }).then(res => {
        if (res && res.code === 0) {
          const result = res.mailProduct;
          const specResults = result.productSpecs;
          const dataSource = [];
          specResults.forEach(r => {
            let productss = '';
            if (r.productSpecs !== undefined) {
              const productSpecs = JSON.parse(r.productSpecs);
              productSpecs.forEach(s => {
                // eslint-disable-next-line guard-for-in,no-restricted-syntax
                for (const key in s) {
                  productss = productss === '' ? s[key] : `${productss},${s[key]}`;
                }
              });
            }
            r.productSpecs = productss;
            dataSource.push(r);
          });
          this.setState({
            data: dataSource,
          });
          return dataSource;
        }
        return [];
      });
    }
  };

  render() {
    const type = this.props.type; //编辑是：新增（add）、编辑(edit)、复制(copy)、还是查看(view)
    const model = this.props.model || {};
    const {
      form,
      form: { getFieldDecorator, getFieldValue, setFieldsValue },
    } = this.props;
    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 8 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
      }, //5+19=24,少一个栅格
    };
    const formItemLayoutV1 = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 4 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 20 },
      }, //5+19=24,少一个栅格
    };
    const colSpanLayout = { md: 12, sm: 24 }; //每一col跨?列
    const rowGutterPxLayout = { md: 24, sm: 16 }; //col之间的间隔?px
    const inputCodeDisabled = {
      disabled: type === 'update',
    };
    const inputCodeDisabledForView = {
      disabled: type === 'view',
    };
    const days = [];
    for (let i = 1; i <= 30; i += 1) {
      if (i.toString().length === 1) {
        days.push(<option key={i}>0{i}</option>);
      } else {
        days.push(<option key={i}>{i}</option>);
      }
    }
    const hours = [];
    for (let i = 0; i < 24; i += 1) {
      if (i.toString().length === 1) {
        hours.push(<option key={i}>0{i}</option>);
      } else {
        hours.push(<option key={i}>{i}</option>);
      }
    }
    const mins = [];
    for (let i = 0; i < 60; i += 1) {
      if (i.toString().length === 1) {
        mins.push(<option key={i}>0{i}</option>);
      } else {
        mins.push(<option key={i}>{i}</option>);
      }
    }
    const columns = [
      {
        title: '规格',
        dataIndex: 'productSpecs',
        key: 'productSpecs',
      },
      {
        title: '商品原价',
        dataIndex: 'originalPrice',
        key: 'originalPrice',
      },
      {
        title: '拼团价',
        dataIndex: 'grouponPrice',
        key: 'grouponPrice',
        render: (record, row) => {
          console.log(row);
          return (
            <Form>
              <FormItem style={{ margin: 0 }}>
                {getFieldDecorator(`grouponPrice-${row.id}`, {
                  rules: [
                    {
                      required: true,
                      message: '请输入商品原价',
                    },
                    rulesReg('money_0_999999'),
                  ],
                  initialValue: record,
                })(<Input style={{ width: '100px' }} />)}
              </FormItem>
            </Form>
          );
        },
      },
      {
        title: '库存',
        dataIndex: 'inventory',
        key: 'inventory',
      },
    ];

    if (model.delayTime) {
      model.delayTimeDay = Math.floor(model.delayTime / 60 / 60 / 24);
      model.delayTimeHour = Math.floor(
        (model.delayTime - model.delayTimeDay * 24 * 60 * 60) / 60 / 60
      );
      model.delayTimeMin = Math.floor(
        (model.delayTime - (model.delayTimeDay * 24 * 60 * 60 + model.delayTimeHour * 60 * 60)) / 60
      );
      if (model.delayTimeDay.toString().length === 1) {
        model.delayTimeDay = `0${model.delayTimeDay}`;
      }
      if (model.delayTimeHour.toString().length === 1) {
        model.delayTimeHour = `0${model.delayTimeHour}`;
      }
      if (model.delayTimeMin.toString().length === 1) {
        model.delayTimeMin = `0${model.delayTimeMin}`;
      }
    }
    const result = [];
    if (type === 'update' || type === 'view') {
      result.push(
        <Option key={model.productId} value={model.productId}>
          {model.productName}
        </Option>
      );
    }
    //校验文档：https://ant.design/components/form-cn/#%E6%A0%A1%E9%AA%8C%E8%A7%84%E5%88%99
    return (
      <Form layout="horizontal" {...formItemLayout}>
        <Row gutter={{ ...rowGutterPxLayout }}>
          <Col {...colSpanLayout}>
            <FormItem label="商品名称" {...formItemLayout}>
              {getFieldDecorator('productId', {
                initialValue: model.productId,
                rules: [
                  {
                    required: true,
                    message: '商品必填',
                  },
                  //rulesReg('number')
                ],
              })(
                <Select
                  showSearch
                  style={{ width: 315 }}
                  placeholder="请选择商品"
                  optionFilterProp="children"
                  {...inputCodeDisabled}
                  {...inputCodeDisabledForView}
                  onChange={this.productChange}
                  // onFocus={this.productSearch}
                  onSearch={this.productSearch}
                  notFoundContent={null}
                >
                  {result}
                  {this.state.productChildren}
                </Select>
              )}
              &nbsp;&nbsp;
              <Tooltip
                placement="right"
                title="如果商品已经参加过其他活动或者参与过正在进行中的拼团活动，则不能参加拼团活动"
              >
                <Icon type="question-circle" />
              </Tooltip>
            </FormItem>
          </Col>
          <Col {...colSpanLayout}>
            <FormItem label="活动名称" {...formItemLayout}>
              {getFieldDecorator('title', {
                initialValue: model.title === undefined ? this.state.title : model.title,
                rules: [
                  {
                    required: true,
                    message: '活动名称必填',
                  },
                  {
                    whitespace: true,
                    message: '不能包含空白符',
                  },
                  {
                    max: 64,
                    message: '最长64个字符',
                  },
                ],
              })(
                <Input
                  type="text"
                  style={{ width: 334 }}
                  autocomplete="off"
                  maxlength={64}
                  {...inputCodeDisabledForView}
                  placeholder="活动名称"
                />
              )}
            </FormItem>
          </Col>
          <Col {...colSpanLayout}>
            <FormItem label="生效时间" {...formItemLayout}>
              {getFieldDecorator('startTimeBetween', {
                initialValue: [
                  moment(model.startTime === undefined ? moment() : model.startTime, 'YYYY/MM/DD'),
                  moment(model.endTime === undefined ? moment() : model.endTime, 'YYYY/MM/DD'),
                ],
                rules: [
                  {
                    required: true,
                    message: '生效时间必填',
                  },
                ],
              })(
                <RangePicker
                  defaultValue={[
                    moment(
                      model.startTime === undefined ? moment() : model.startTime,
                      'YYYY/MM/DD'
                    ),
                    moment(model.endTime === undefined ? moment() : model.endTime, 'YYYY/MM/DD'),
                  ]}
                  {...inputCodeDisabled}
                  {...inputCodeDisabledForView}
                />
              )}
            </FormItem>
          </Col>
          <Col {...colSpanLayout}>
            <FormItem label="参团人数" {...formItemLayout}>
              {getFieldDecorator('joinNum', {
                initialValue: model.joinNum === undefined ? 5 : model.joinNum,
                rules: [
                  {
                    required: true,
                    message: '参团人数必填',
                  },
                  rulesReg('number'),
                ],
              })(
                <InputNumber
                  min={1}
                  max={50}
                  style={{ width: 334 }}
                  autocomplete="off"
                  {...inputCodeDisabled}
                  {...inputCodeDisabledForView}
                  placeholder="参团人数"
                />
              )}
            </FormItem>
          </Col>
          <Col {...colSpanLayout}>
            <FormItem label="拼团有效期" {...formItemLayout}>
              <Row>
                <Col>
                  {getFieldDecorator('delayTimeDay', {
                    initialValue: model.delayTimeDay === undefined ? '01' : model.delayTimeDay,
                    rules: [
                      {
                        required: true,
                        message: '拼团有效期必填',
                      },
                    ],
                  })(
                    <Select
                      style={{ width: 85 }}
                      {...inputCodeDisabled}
                      {...inputCodeDisabledForView}
                    >
                      {days}
                    </Select>
                  )}
                  &nbsp;日&nbsp;
                  {getFieldDecorator('delayTimeHour', {
                    initialValue: model.delayTimeHour === undefined ? '00' : model.delayTimeHour,
                    rules: [
                      {
                        required: true,
                        message: '拼团有效期必填',
                      },
                    ],
                  })(
                    <Select
                      style={{ width: 85 }}
                      {...inputCodeDisabled}
                      {...inputCodeDisabledForView}
                    >
                      {hours}
                    </Select>
                  )}
                  &nbsp;时&nbsp;
                  {getFieldDecorator('delayTimeMin', {
                    initialValue: model.delayTimeMin === undefined ? '00' : model.delayTimeMin,
                    rules: [
                      {
                        required: true,
                        message: '拼团有效期必填',
                      },
                    ],
                  })(
                    <Select
                      style={{ width: 85 }}
                      {...inputCodeDisabled}
                      {...inputCodeDisabledForView}
                    >
                      {mins}
                    </Select>
                  )}
                  &nbsp;分&nbsp;
                  <Tooltip
                    placement="right"
                    title="若设置1日，用户开团后，需要在1日内成团，超时则拼团失败"
                  >
                    <Icon type="question-circle" />
                  </Tooltip>
                </Col>
              </Row>
            </FormItem>
          </Col>
          <Col {...colSpanLayout}>
            <FormItem label="商品限购" {...formItemLayout}>
              <Row>
                <Col>
                  {getFieldDecorator('limitNumStatus', {
                    initialValue: model.limitNumStatus,
                    rules: [
                      {
                        required: false,
                        message: '商品限购必填',
                      },
                    ],
                  })(
                    <Checkbox
                      defaultChecked={model.limitNumStatus}
                      onChange={e => {
                        model.limitNumStatus = e.target.checked;
                        model.limitNum = e.target.checked ? model.limitNum : 0;
                      }}
                      {...inputCodeDisabledForView}
                    >
                      开启限购
                    </Checkbox>
                  )}
                  {getFieldDecorator('limitNum', {
                    initialValue: model.limitNum,
                    rules: [
                      {
                        required: false,
                        message: '商品限购必填',
                      },
                    ],
                  })(<InputNumber min={0} max={50} disabled={!model.limitNumStatus} />)}
                  <span>&nbsp;&nbsp;件/人</span>
                </Col>
              </Row>
            </FormItem>
          </Col>
          <Col {...colSpanLayout}>
            <FormItem label="凑团设置" {...formItemLayout}>
              <Row>
                <Col>
                  {getFieldDecorator('autoGroupEnabled', {
                    initialValue: model.autoGroupEnabled,
                    rules: [
                      {
                        required: false,
                        message: '自动凑团必填',
                      },
                    ],
                  })(
                    <Checkbox
                      checked={model.autoGroupEnabled}
                      onChange={e => {
                        model.autoGroupEnabled = e.target.checked;
                      }}
                      {...inputCodeDisabledForView}
                    >
                      开启凑团
                    </Checkbox>
                  )}
                  <Tooltip
                    placement="right"
                    title="开启凑团后，对于未参团的买家，活动商品详情页会显示未成团的团列表，买家可以直接任选一个参团，提升成团率。"
                  >
                    <Icon type="question-circle" />
                  </Tooltip>
                </Col>
              </Row>
            </FormItem>
          </Col>
          <Col {...colSpanLayout}>
            <FormItem label="优惠叠加" {...formItemLayout}>
              {getFieldDecorator('isOverlayAssets', {
                initialValue: model.isOverlayAssets,
                rules: [
                  {
                    required: false,
                    message: '优惠叠加必填',
                  },
                ],
              })(
                <Checkbox defaultChecked={model.isOverlayAssets} {...inputCodeDisabledForView}>
                  可叠加使用优惠券/优惠码
                </Checkbox>
              )}
            </FormItem>
          </Col>
          <Col {...colSpanLayout}>
            <FormItem label="租户" {...formItemLayout}>
              {getFieldDecorator('tenantId', {
                initialValue: model.tenantId === undefined ? 1 : model.tenantId,
                rules: [
                  {
                    required: true,
                    message: '租户',
                  },
                ],
              })(
                <InputNumber
                  autocomplete="off"
                  min={0}
                  max={1000}
                  disabled
                  style={{ width: '330px' }}
                  placeholder="租户:默认为1"
                />
              )}
            </FormItem>
          </Col>
          <Col {...colSpanLayout}>
            <FormItem label="微信二维码" {...formItemLayout}>
              {getFieldDecorator('wxQrCode', {
                initialValue: model.wxQrCode,
                rules: [],
              })(
                <div className="clearfix">
                  <DefaultImage style={{ width: '50%', height: '50%' }} src={model.wxQrCode} />
                </div>
              )}
            </FormItem>
          </Col>
        </Row>
        <Row gutter={{ ...rowGutterPxLayout }}>
          <Col md={30} sm={20}>
            <FormItem label="价格设置" {...formItemLayoutV1}>
              {getFieldDecorator('priceSet', {
                initialValue: model.priceSet,
                rules: [
                  {
                    required: false,
                    message: '价格设置',
                  },
                ],
              })(
                <Table
                  columns={columns}
                  bordered
                  dataSource={
                    this.state.data === undefined
                      ? this.getProductInfo(model.productId)
                      : this.state.data
                  }
                  {...inputCodeDisabledForView}
                  // style={{ width: 500 }}
                />
              )}
            </FormItem>
          </Col>
        </Row>
      </Form>
    );
  }
}

/* eslint-disable no-class-assign */
//无更多的绑定， 请用 @Form.create() 注解替换
EditForm = Form.create({})(EditForm);
